package dyl.sys.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import dyl.common.util.DylSqlUtil;
import dyl.common.util.JdbcTemplateUtil;
import dyl.common.util.Page;
import dyl.sys.bean.SysRole;
import dyl.sys.init.AuthCache;
/**

 * @author Dyl
 * 2017-04-05 15:42:37
 */
@Service
public class SysRoleServiceImpl {
	@Resource
	private JdbcTemplateUtil jdbcTemplate;
	@Resource 
	SysRoleUserServiceImpl sysRoleUserServiceImpl;
	@Resource
	private AuthCache authCache;
	/**
	 * 说明：分页查询表sys_role记录封装成List集合
	 * @return JSONObject
	 */
	public List<SysRole>  findSysRoleList(Page page,SysRole sysRole) throws Exception{
		String sql = "select * from sys_role t where id > 1";
		List<Object> con = new ArrayList<Object>();
		if(StringUtils.isNotEmpty(sysRole.getName())){
			sql+=" and t.name like ?";
			con.add("%"+sysRole.getName()+"%");
		}
		List<SysRole> sysRoleList =  jdbcTemplate.queryForListBeanByPage(sql, con, SysRole.class, page);
		
		return sysRoleList;
	}
	/**
	 * 查询可分配的角色
	 * @return
	 * @throws Exception
	 */
	public List<SysRole>  findAuthSysRoleList() throws Exception{
		List<SysRole> sysRoleList =  jdbcTemplate.queryForListBean("select id,name,note,creator,create_time from sys_role t where t.id>0", SysRole.class);
		return sysRoleList;
	}
	/**
	 * 说明：根据主键查询表sys_role中的一条记录 
	 * @return SysRole
	 */
	public SysRole getSysRole(BigDecimal  id) throws Exception{
		String sql = "select id,name,note,creator,create_time from sys_role where id=?";
		SysRole sysRole  = jdbcTemplate.queryForBean(sql, new Object[]{id},SysRole.class); 
		return sysRole;
	}
	/**
	 * 说明：往表sys_role中插入一条记录
	 * @return int >0代表操作成功
	 */
	@Transactional
	public int insertSysRole(SysRole sysRole,String authRoles,String oldAuthRoles) throws Exception{
		String sql = "insert into sys_role(id,name,note,creator) values("+DylSqlUtil.getnextSeqNextVal()+",?,?,?)";
		int returnVal=jdbcTemplate.update(sql,new Object[]{sysRole.getName(),sysRole.getNote(),sysRole.getCreator()});
		//sysRoleUserServiceImpl.updateRoleUser(authRoles, oldAuthRoles,sysRole.getCreator());
		return returnVal;
	}
	/**
	 * 说明：根据主键更新表sys_role中的记录
	 * @return int >0代表操作成功
	 */
	@Transactional
	public int updateSysRole(SysRole sysRole,String authRoles,String oldAuthRoles) throws Exception{
		String sql = "update sys_role t set ";
		List<Object> con = new ArrayList<Object>();
		if(sysRole.getName()!=null){
			sql+="t.name=?,";
			con.add(sysRole.getName());
		}
		if(sysRole.getNote()!=null){
			sql+="t.note=?,";
			con.add(sysRole.getNote());
		}
		sql=sql.substring(0,sql.length()-1);
		sql+=" where id=?";
		con.add(sysRole.getId());
		int returnVal=jdbcTemplate.update(sql,con.toArray());
		return returnVal;
	}
	/**
	 * 说明：根据主键删除表sys_role中的记录
	 * @return int >0代表操作成功
	 */
	@Transactional
	public int[] deleteSysRole(String  ids) throws Exception{
		//1清空该角色所有权限
		String deleteRoleAuths = "delete from sys_auth_role where role_id= ? ";
		//2.清空该角色下的用户
		String deleteRoleUser = "delete from sys_role_user where roleid = ?";
		//jdbcTemplate.update(,new Object[]{roleId});
		String sql = "delete from  sys_role where id=?";
		String[] idArr  =  ids.split(",");
		List<Object[]> paraList = new ArrayList<Object[]>(); 
		for (int i = 0; i < idArr.length; i++){
			if(Integer.parseInt(idArr[i])<=10)continue;//不允许删除默认角色
			paraList.add(new Object[]{idArr[i]});
		}
		jdbcTemplate.batchUpdate(deleteRoleAuths,paraList);
		jdbcTemplate.batchUpdate(deleteRoleUser,paraList);
		
		return jdbcTemplate.batchUpdate(sql,paraList);
	}
	/**
	 * 保存角色权限
	 * @param authRoleKinds
	 * @return
	 */
	@Transactional
	public int saveAuth(String authRoleKinds,BigDecimal roleId){
		//1清空该角色所有权限
		jdbcTemplate.update("delete from sys_auth_role where role_id= ? ",new Object[]{roleId});
		//2.保存角色权限
		if(StringUtils.isNotEmpty(authRoleKinds)){
			String[] authRoleKindArr = authRoleKinds.split(",");
			String insertSql = "insert into sys_auth_role(id, role_id, menu_id, kind_id) values("+DylSqlUtil.getnextSeqNextVal()+",?,?,?)";
			List<Object[]> paras = new ArrayList<Object[]>();
			for (int i = 0; i < authRoleKindArr.length; i++){
				String[] role_kind = authRoleKindArr[i].split("_");
				paras.add(new Object[]{roleId,role_kind[0],role_kind[1]});
			}
			jdbcTemplate.batchUpdate(insertSql, paras);
		}
		//更新权限缓存
		authCache.cacheRoleAuth(roleId);
		return 1;
	}
}
